package com.fenghongzhang.sample.recycleview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.fenghongzhang.sample.Food
import com.fenghongzhang.sample.R
import kotlinx.android.synthetic.main.recycle_view_layout.view.*

class FoodRecycleViewAdapter(private val data:List<Food>) : RecyclerView.Adapter<FoodRecycleViewAdapter.ViewHolder>() {

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val pic: ImageView = itemView.rv_image
        val name: TextView = itemView.rv_name
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.recycle_view_layout,parent,false)
        val viewHolder = ViewHolder(view)
        viewHolder.name.setOnClickListener{
            //取到当前的位置
            val position  = viewHolder.adapterPosition
            Toast.makeText(parent.context,data[position].name,Toast.LENGTH_LONG).show()
        }
        viewHolder.pic.setOnClickListener{
            Toast.makeText(parent.context,"haha",Toast.LENGTH_LONG).show()
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val food = data[position]
        food.pic?.let { holder.pic.setImageResource(it) }
        holder.name.text = food?.name
    }

    override fun getItemCount(): Int {
        return data.size
    }

}